<template>
  <div class="login">
    <van-nav-bar title="账号登录"  >
      <template #left>
        <van-icon color="#fff" name="arrow-left" @click="onClickLeft" />
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="fm.username"
        name="用户名"
        placeholder="请输入账号"
        :rules="rules.username"
      />
      <van-field
        v-model="fm.password"
        type="password"
        name="密码"
        placeholder="请输入密码"
        :rules="rules.pasword"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">登陆</van-button>
      </div>
    </van-form>
    <div id="box" @click="$router.push('/registered')">
      <p>还没有账号，去注册~</p>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { Toast } from 'vant'
export default {
  data () {
    return {
      fm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{4,6}$/, message: '用户名4到6位' }
        ],
        pasword: [
          { required: true, message: '请填写密码' },
          { pattern: /^\w{5,12}$/, message: '密码6到12位字母或数字' }
        ]
      }
    }
  },

  created () {},

  methods: {
    ...mapMutations(['setToken']),
    onClickLeft () {
      this.$router.back()
    },
    async onSubmit () {
      try {
        const res = await this.$axios({
          url: '/user/login',
          method: 'post',
          data: this.fm
        })
        this.setToken(res.data.body.token)
        Toast.success('登录成功')
        setTimeout(() => {
          this.$router.push('/layout/my')
        }, 1000)
      } catch (err) {
        Toast.fail(err.message)
      }
    }
  }
}
</script>

<style scoped lang="less">
.login {
  #box {
    text-align: center;
  }
  .van-button--info {
    background-color: #21b97a;
    border: none;
  }
  p {
    color: #666;
    font-size: 14px;
  }
  /deep/.van-field__body {
    height: 60px;
    input {
      height: 60px;
    }
  }
}
</style>
